package br.com.gsc.vaadin;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import javax.imageio.ImageIO;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;

import br.com.gsc.helper.ImageResizerHelper;
import br.com.gsc.model.tableMapping.Admin;
import br.com.gsc.model.tableMapping.Company;
import br.com.gsc.model.tableMapping.Person;
import br.com.gsc.repository.objRepos.CompanyRepository;
import br.com.gsc.repository.objRepos.PersonRepository;
import br.com.gsc.setup.AuthenticationHolder;

import com.vaadin.annotations.AutoGenerated;
import com.vaadin.ui.AbsoluteLayout;
import com.vaadin.ui.Alignment;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.CustomComponent;
import com.vaadin.ui.GridLayout;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.Label;
import com.vaadin.ui.Panel;
import com.vaadin.ui.ProgressIndicator;
import com.vaadin.ui.RichTextArea;
import com.vaadin.ui.TextField;
import com.vaadin.ui.Upload;
import com.vaadin.ui.Upload.FailedEvent;
import com.vaadin.ui.Upload.FinishedEvent;
import com.vaadin.ui.Upload.Receiver;
import com.vaadin.ui.Upload.StartedEvent;
import com.vaadin.ui.Upload.SucceededEvent;
import com.vaadin.ui.VerticalLayout;

@Configurable(preConstruction=true)
public class AddCompanyWindow extends CustomComponent {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	@AutoGenerated
	private AbsoluteLayout mainLayout;
	@AutoGenerated
	private Panel panel_1;
	@AutoGenerated
	private VerticalLayout verticalLayout_2;
	@AutoGenerated
	private Panel panel_7;
	@AutoGenerated
	private GridLayout gridLayout_2;
	@AutoGenerated
	private Upload upload;
	@AutoGenerated
	private Button button_1;
	@AutoGenerated
	private RichTextArea richTextArea_2;
	@AutoGenerated
	private Label label_7;
	@AutoGenerated
	private TextField textField_3;
	@AutoGenerated
	private Label label_4;
	@AutoGenerated
	private Panel panel_5;
	@AutoGenerated
	private VerticalLayout verticalLayout_6;
	@AutoGenerated
	private Label label_3;
	private MyReceiver receiver = new MyReceiver();
	private ProgressIndicator pi = new ProgressIndicator();
	private HorizontalLayout progressLayout = new HorizontalLayout();
	private static File file;

	/*- VaadinEditorProperties={"grid":"RegularGrid,20","showGrid":true,"snapToGrid":true,"snapToObject":true,"movingGuides":false,"snappingDistance":10} */

	private Person p;
	private Admin admin;
	
	@Autowired
	private CompanyRepository cr;
	@Autowired
	private PersonRepository pRepo;
	@Autowired
	private PersonRepository pRepo2;	
	@Autowired
	private AuthenticationHolder auth;
	
	/**
	 * The constructor should first build the main layout, set the
	 * composition root and then do any custom initialization.
	 *
	 * The constructor will not be automatically regenerated by the
	 * visual editor.
	 */
	public AddCompanyWindow() {
		buildMainLayout();
		setCompositionRoot(mainLayout);
		setupAddButtonListener();
		p = pRepo.findPersonByID(auth.getAuthentication().getName());
		if(p instanceof Admin){
			admin = (Admin)p;
		}
//		this.customizeLayout();
	}
	
	public void setupUploadListener(){
		
		/**
         * =========== Add needed listener for the upload component: start,
         * progress, finish, success, fail ===========
         */

        upload.addListener(new Upload.StartedListener() {
            public void uploadStarted(StartedEvent event) {
                // This method gets called immediatedly after upload is started
                upload.setVisible(false);
                progressLayout.setVisible(true);
                pi.setValue(0f);
                pi.setPollingInterval(500);
                System.out.println("Start");
//                status.setValue("Uploading file \"" + event.getFilename()
//                        + "\"");
            }
        });

        upload.addListener(new Upload.ProgressListener() {
            public void updateProgress(long readBytes, long contentLength) {
                // This method gets called several times during the update
                pi.setValue(new Float(readBytes / (float) contentLength));
            }

        });

        upload.addListener(new Upload.SucceededListener() {
            public void uploadSucceeded(SucceededEvent event) {
                // This method gets called when the upload finished successfully
//                status.setValue("Uploading file \"" + event.getFilename()
//                        + "\" succeeded");
            	System.out.println("Sucess");
            }
        });

        upload.addListener(new Upload.FailedListener() {
            public void uploadFailed(FailedEvent event) {
                // This method gets called when the upload failed
//                status.setValue("Uploading interrupted");
            	System.out.println("Failed");
            }
        });

        upload.addListener(new Upload.FinishedListener() {
            public void uploadFinished(FinishedEvent event) {
                // This method gets called always when the upload finished,
                // either succeeding or failing
                progressLayout.setVisible(false);
                upload.setVisible(true);
                upload.setCaption("Select another file");               
            }
        });
	}
	
	public void setupAddButtonListener(){
		button_1.addListener(new Button.ClickListener() {
			
			/**
			 * 
			 */
			private static final long serialVersionUID = 1L;

			@Override
			public void buttonClick(ClickEvent event) {
				Company comp = new Company();
				comp.setName(textField_3.getValue().toString());
				comp.setDescription(richTextArea_2.getValue().toString());
				comp.addOwner(admin);
				
				String filename=null;
				if(file != null){	
	                BufferedImage img;
					try {
						img = ImageIO.read(new File("C:/Users/cristiano/workspace/roo/src/main/webapp/img/Logos/"+file.getName()));			
						int type = img.getType() == 0? BufferedImage.TYPE_INT_ARGB : img.getType();
						BufferedImage imgResize = ImageResizerHelper.resizeImage(img, type);                
						File image = new File("C:/Users/cristiano/workspace/roo/src/main/webapp/img/Logos/small_"+file.getName());
						ImageIO.write(imgResize, "png", image);
						filename="small_"+file.getName();						
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				
				if(file != null && filename != null){
					comp.setCompanyImage(filename);
				}else{
					comp.setCompanyImage("thumb_default_company.png");
				}
				
				Admin a = (Admin) pRepo2.findPersonByID(admin.getUsername());
				a.addCompany(comp);
				pRepo2.updatePerson(a);
				
				cr.addCompany(comp);
				getWindow().showNotification("Empresa Gravada!");
			}
		});
	}

//	public void customizeLayout(){
//		
//		this.label_3.addStyleName("teste_vaadin");
//		
//	}

	@AutoGenerated
	private AbsoluteLayout buildMainLayout() {
		// common part: create layout
		mainLayout = new AbsoluteLayout();
		mainLayout.setImmediate(false);
		mainLayout.setWidth("100%");
		mainLayout.setHeight("100%");
		mainLayout.setMargin(false);
		
		// top-level component properties
		setWidth("100.0%");
		setHeight("100.0%");
		
		// panel_1
		panel_1 = buildPanel_1();
		mainLayout.addComponent(panel_1,
				"top:0.0px;right:-5.0px;bottom:-9.0px;left:0.0px;");
		
		return mainLayout;
	}

	@AutoGenerated
	private Panel buildPanel_1() {
		// common part: create layout
		panel_1 = new Panel();
		panel_1.setImmediate(false);
		panel_1.setWidth("100.0%");
		panel_1.setHeight("100.0%");
		
		// verticalLayout_2
		verticalLayout_2 = buildVerticalLayout_2();
		panel_1.setContent(verticalLayout_2);
		
		return panel_1;
	}

	@AutoGenerated
	private VerticalLayout buildVerticalLayout_2() {
		// common part: create layout
		verticalLayout_2 = new VerticalLayout();
		verticalLayout_2.setImmediate(false);
		verticalLayout_2.setWidth("100.0%");
		verticalLayout_2.setHeight("-1px");
		verticalLayout_2.setMargin(true);
		verticalLayout_2.setSpacing(true);
		
		// panel_5
		panel_5 = buildPanel_5();
		verticalLayout_2.addComponent(panel_5);
		
		// panel_7
		panel_7 = buildPanel_7();
		verticalLayout_2.addComponent(panel_7);
		verticalLayout_2.setExpandRatio(panel_7, 1.0f);
		
		return verticalLayout_2;
	}

	@AutoGenerated
	private Panel buildPanel_5() {
		// common part: create layout
		panel_5 = new Panel();
		panel_5.setStyleName("bordless");
		panel_5.setImmediate(false);
		panel_5.setDescription("Cadastrar Empresas");
		panel_5.setWidth("100.0%");
		panel_5.setHeight("40px");
		
		// verticalLayout_6
		verticalLayout_6 = buildVerticalLayout_6();
		panel_5.setContent(verticalLayout_6);
		
		return panel_5;
	}

	@AutoGenerated
	private VerticalLayout buildVerticalLayout_6() {
		// common part: create layout
		verticalLayout_6 = new VerticalLayout();
		verticalLayout_6.setImmediate(false);
		verticalLayout_6.setWidth("100.0%");
		verticalLayout_6.setHeight("100.0%");
		verticalLayout_6.setMargin(false);
		
		// label_3
		label_3 = new Label();
		label_3.setStyleName("lbl_big");
		label_3.setImmediate(false);
		label_3.setWidth("100.0%");
		label_3.setHeight("100.0%");
		label_3.setValue("Cadastrar Empresas");
		verticalLayout_6.addComponent(label_3);
		
		return verticalLayout_6;
	}

	@AutoGenerated
	private Panel buildPanel_7() {
		// common part: create layout
		panel_7 = new Panel();
		panel_7.setStyleName("bordless");
		panel_7.setImmediate(false);
		panel_7.setWidth("100.0%");
		panel_7.setHeight("100.0%");
		
		// gridLayout_2
		gridLayout_2 = buildGridLayout_2();
		panel_7.setContent(gridLayout_2);
		
		return panel_7;
	}

	@AutoGenerated
	private GridLayout buildGridLayout_2() {
		// common part: create layout
		gridLayout_2 = new GridLayout();
		gridLayout_2.setImmediate(false);
		gridLayout_2.setWidth("100.0%");
		gridLayout_2.setHeight("100.0%");
		gridLayout_2.setMargin(true);
		gridLayout_2.setSpacing(true);
		gridLayout_2.setRows(10);
		
		// label_4
		label_4 = new Label();
		label_4.setStyleName("lbl_small");
		label_4.setImmediate(false);
		label_4.setWidth("-1px");
		label_4.setHeight("-1px");
		label_4.setValue("Nome da Empresa");
		gridLayout_2.addComponent(label_4, 0, 0);
		
		// textField_3
		textField_3 = new TextField();
		textField_3.setStyleName("stl-text-field");
		textField_3.setImmediate(false);
		textField_3.setWidth("100.0%");
		textField_3.setHeight("-1px");
		textField_3.setSecret(false);
		gridLayout_2.addComponent(textField_3, 0, 1);
		
		// label_7
		label_7 = new Label();
		label_7.setStyleName("lbl_small");
		label_7.setImmediate(false);
		label_7.setWidth("-1px");
		label_7.setHeight("-1px");
		label_7.setValue("Historia da empresa");
		gridLayout_2.addComponent(label_7, 0, 2);
		
		// richTextArea_2
		richTextArea_2 = new RichTextArea();
		richTextArea_2.setStyleName("stl-textarea-field");
		richTextArea_2.setImmediate(false);
		richTextArea_2.setWidth("100.0%");
		richTextArea_2.setHeight("-1px");
		gridLayout_2.addComponent(richTextArea_2, 0, 3);
		
		// button_1
		button_1 = new Button();
		button_1.setStyleName("btn_save");
		button_1.setCaption("Gravar empresa");
		button_1.setImmediate(true);
		button_1.setWidth("150px");
		button_1.setHeight("-1px");
		gridLayout_2.addComponent(button_1, 0, 5);
		gridLayout_2.setComponentAlignment(button_1, new Alignment(10));
		
		// upload_1
		upload = new Upload(null,receiver);
		upload.setImmediate(false);
		upload.setWidth("-1px");
		upload.setHeight("-1px");
		gridLayout_2.addComponent(upload, 0, 4);
//		gridLayout_2.addComponent(progressLayout,0,4);
		
		
		return gridLayout_2;
	}
	
    public static class MyReceiver implements Receiver {

		private static final long serialVersionUID = 1L;
		private String fileName;
        private String mtype;		
        
        public OutputStream receiveUpload(String filename, String mimetype) {
                FileOutputStream fos = null; // Output stream to write to
                file = new File("C:/Users/cristiano/workspace/roo/src/main/webapp/img/Logos/"+filename);                
                
                try {
                    // Open the file for writing.
                    fos = new FileOutputStream(file);                    
                } catch (final java.io.FileNotFoundException e) {
                    // Error while opening the file. Not reported here.
                    e.printStackTrace();
                    return null;
                }
                
                return fos; // Return the output stream to write to
        }

        public String getFileName() {
            return fileName;
        }

        public String getMimeType() {
            return mtype;
        }

    }

}
